//
//  HomeViewController.swift
//  WeiBo
//
//  Created by LTX on 2016/10/29.
//  Copyright © 2016年 LTX. All rights reserved.
//

import UIKit
import SDWebImage

class HomeViewController: BaseViewController {
    
    //懒加载属性
    fileprivate  lazy var titleBtn : TitleButton = TitleButton()
    
    fileprivate lazy  var popoverAnimte :PopoverAnimate = PopoverAnimate {[weak self] (isShow) in
        self?.titleBtn.isSelected = isShow
    }
    
    
    //所有微博模型数组
    fileprivate lazy var statusModelArray : [StatusViewModel] = [StatusViewModel]()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
    
        
            // MARK:- 没有登录状态设置内容
            
            // MARK:- 添加动画
            guestView.addBackViewAnim()
            if !isLogin {
                return
            }
        
            // MARK:- 设置UI
            setUI()
        
            // MARK:- 设置导航栏内容
            setNavigationBar()
        
        
            // 加载首页数据
            loadStatusDate()
            
        }
    

  
}

// MARK:- 设置UI
extension HomeViewController{
    
  fileprivate  func setNavigationBar() {
    
    // MARK:- 左边按钮
    navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
    
    // MARK:- 右侧按钮
    navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
    
    // MARK:- 设置标题
    titleBtn.setTitle("码宝宝", for: .normal)
    titleBtn.addTarget(self, action: #selector(titleBtnClick), for: .touchUpInside)
    navigationItem.titleView = titleBtn
    
    }
    
    // MARK:- 设置UI
  fileprivate  func setUI() {
    
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200;
    }
    
    
}

// MARK:- 事件监听
extension HomeViewController{
    func titleBtnClick(_ btn: UIButton) {
        
        // 1. 改变按钮状态
        btn.isSelected = !btn.isSelected
        
        // 2.创建弹出的控制器
        let popoverView = PopoverViewController()
        
        // 3.设置控制器的model样式 custom不会移除tabbar等视图
        popoverView.modalPresentationStyle = .custom
        
        // 4.转场代理
        popoverView.transitioningDelegate = popoverAnimte
        popoverAnimte.presentFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
        
        // 5. 弹出控制器
        present(popoverView, animated: true, completion: nil)
        
        
    }
    
}


// MARK:- 请求微博数据
extension HomeViewController{

    fileprivate func loadStatusDate() {
        
        NetworkTools.shareInstance.loadStatuses { (result, error) in
            
            if error != nil{
                return
            }

            guard let statusArray = result else{
            
                print("没有数据")
                return
            }
            
            for statueDic in statusArray{
                
                let statusModel = StatusModel(dic: statueDic)
                let viewModel = StatusViewModel(status: statusModel)
                self.statusModelArray.append(viewModel)
                
            }
            
            print("微博数量：\(self.statusModelArray.count)")
            
            //缓存图片
            self.cacheImages(viewModel: self.statusModelArray)
            
            //刷新列表
//          self.tableView.reloadData()
            
        }
        
    }
    
    //缓存图片
    fileprivate func cacheImages(viewModel : [StatusViewModel]){
        
        //创建group
        let group = DispatchGroup.init()
        
        
        for model in viewModel {
            
            for picURL in model.picURLArray {
                
                
                group.enter()
                
                
                SDWebImageManager.shared().downloadImage(with: picURL as URL!, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    
                    print("下载了一张图片")
                    
                    group.leave()
                    
                })
            }
            
        }
        
        //刷新表格
        group.notify(queue: DispatchQueue.main, work: DispatchWorkItem.init(block: {
            
        
            //刷新
            self.tableView .reloadData()
        }))
        
    }

}


// MARK:- Tableview代理方法
extension HomeViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.statusModelArray.count
    }
    

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeCell
        
        let  viewModel = self.statusModelArray[indexPath.row]

        cell.viewModel = viewModel
        
                
//        cell.textLabel?.text = viewModel.createAtText
//        print("微博数量：\(viewModel.createAtText)")

        
        return cell
        
    }

}





